package com.litong.litongjiaoyu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.litong.litongjiaoyu.annotation.IgnoreAuth;
import com.litong.litongjiaoyu.entity.SysChatrecord;
import com.litong.litongjiaoyu.service.SysChatrecordService;
import com.litong.litongjiaoyu.utils.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * (SysChatrecord)表控制层
 *
 * @author jingzepei
 * @since 2020-06-02 10:53:36
 */
@RestController
@RequestMapping("chatrecord")
public class SysChatrecordController {
    /**
     * 日志，门面模式
     */
    private Logger LOGGER = LoggerFactory.getLogger(SysChatrecordController.class);
    
    /**
     * 服务对象
     */
    @Resource
    private SysChatrecordService sysChatrecordService;

    /**
     * 通过主键查询单条数据
     *
     * @param jsonObject 查询起始位置，查询行数，记录表ID
     * @return 多条数据
     */
    @IgnoreAuth
    @PostMapping("get")
    @ResponseBody
    public JSONResult select(@RequestBody JSONObject jsonObject) {
        LOGGER.info(JSON.toJSONString(jsonObject));
        
        
        //获取搜索的起始位置和搜索条数
        int offset = jsonObject.getInteger("offset");
        int limit = jsonObject.getInteger("limit");
        
        JSONObject result = new JSONObject();
        
        //获取消息总个数
        if (jsonObject.getBoolean("first")) {
            result.put(
                    "num",
                    this.sysChatrecordService.countChatRecord(
                            jsonObject.getString("ID")
                    )
            );
        }

        result.put("messageList",
                this.sysChatrecordService.queryAllByLimit(
                        offset,
                        limit,
                        jsonObject.getString("ID")
                )
        );
        
        return JSONResult.ok(result);
    }

    /**
     * 搜索聊天记录
     * @param text 要搜索的内容
     * @return 查询到的内容
     */
    @IgnoreAuth
    @GetMapping("search/{text}")
    public JSONResult search(@PathVariable("text") String text) {

        List<SysChatrecord> sysChatrecords =  this.sysChatrecordService.search(URLDecoder.decode(text, StandardCharsets.UTF_8));

        if (sysChatrecords != null) {
            return JSONResult.ok(sysChatrecords);
        } else {
            return JSONResult.ok();
        }

    }

}